const path = require('path');
const express = require('express');
const favicon = require('serve-favicon');
const webpack = require('webpack');
const engine = require('ejs-locals');

const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require("webpack-Hot-middleware");
const webpackConfig = require('./webpack.dev.config');

const app = express(),
    DIST_DIR = path.join(__dirname, "public"), // 设置静态访问文件路径
    PORT = 9000,
    complier = webpack(webpackConfig);

app.engine('.html', engine);
app.set('views', './app/views/pages');
app.set('view engine', 'html');

let devMiddleware = webpackDevMiddleware(complier, {
    publicPath: webpackConfig.output.publicPath,
    quiet: false, // 向控制台显示任何内容
    noInfo: false, // 显示错误信息到控制台（仅警告和错误）
    watch: true,
    watchOptions: {
        ignored: /node_modules/, //忽略不用监听变更的目录
        aggregateTimeout: 500, //防止重复保存频繁重新编译,500毫米内重复保存不打包
        poll:1000 //每秒询问的文件变更的次数
    }, // watch options (only lazy: false)
    stats: { colors: true }, // 用于形成统计信息的选项
    serverSideRender: false, // 关闭服务器端渲染模式。有关详细信息，请参阅服务器端渲染部分。
});

let hotMiddleware = webpackHotMiddleware(complier, {
    log: false,
    heartbeat: 1000
});

app.use(devMiddleware);

app.use(hotMiddleware);

require('./config/routes')(app);

app.use(favicon(path.join(__dirname, 'favicon.ico')));
app.use(express.static(DIST_DIR)); // 设置访问静态文件的路径

/*
app.listen(PORT, () => {
    console.log("成功启动：localhost:"+ PORT);
});
*/
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.use(function(socket, next){
    if (socket.request.headers.cookie) return next();
    next(new Error('Authentication error'));
});
io.on('connection', function(socket){
    // socket.send('连接成功');
    socket.emit('message', '连接成功');

    socket.on('message', function(data){
        console.log(data);
    });

    socket.on('disconnect', function(){
        console.log('断开连接');
    });

    // 全局广播
    socket.broadcast.emit('DATA', '欢迎使用');

    // 局部广播
    socket.broadcast.to('chat').emit('DATA', '今天天气晴');
});
io.of('chat').on('connection', function(socket){
    socket.emit('message', '欢迎进入【chat】room');
});
server.listen(PORT, () => {
    console.log("成功启动：localhost:" + PORT);
});